#include "msg/MsgHandleBind.h"
#include "msg/MsgHandleThread.h"

namespace KEngine
{	
	MsgHandleThread::MsgHandleThread(unsigned long sleep_ms,const char* name):
	_sleep_ms(sleep_ms),_name(name)
	{
		_thread = new KCore::Thread();
		_handle_map = new MsgHandleBindMap;
	}

	MsgHandleThread::~MsgHandleThread()
	{
		if(_thread)
		{
			if(_thread->isThreadRun())
				_thread->endThread();

			delete _thread;
		}

		delete _handle_map;
	}


	void MsgHandleThread::begin()
	{
		if(_thread)
		{
			_thread->runThread(this);
		}
	}

	void MsgHandleThread::end()
	{
		if(_thread)
		{
			_thread->endThread();
		}
	}

	bool MsgHandleThread::isRunning() const
	{
		if(!_thread)
			return false;

		return _thread->isThreadRun();
	}

	unsigned long MsgHandleThread::threadRun()
	{
		while(_thread->waitKillEvent(_sleep_ms))
		{
			_handle_map->handleOnce();
		}
		return 0;
	}

	void MsgHandleThread::add(std::string& name,MsgHandleBind* set)
	{
		KCore::MutexLock(&_mutex.m_t);
		_handle_map->add(name,set);
	}
	void MsgHandleThread::remove(std::string& name)
	{
		KCore::MutexLock(&_mutex.m_t);
		_handle_map->remove(name);
	}
};
